import asyncio
import logging
import os

from aiogram import Bot
from aiogram.types import FSInputFile
from fluentogram import TranslatorRunner

from src.infrastructure.constants import MEDIA_FOLDER
from src.infrastructure.db.models import Server
from src.infrastructure.qr_generator import generate_qr_code
from src.infrastructure.ssh.async_ssh_connector import generate_vpn_config
from src.infrastructure.utils.helpers import write_to_file
from src.presentation.tg_bot.services.tg_helpers import send_document
from src.presentation.tg_bot.worker.exception_handler import exception_handler

logger = logging.getLogger(__name__)


@exception_handler
async def generate_vpn_config_job(
    ctx,
    server: Server,
    locale: TranslatorRunner,
    telegram_id: int,
    order_id: int,
) -> None:
    bot: Bot = ctx["bot"]

    vpn_config = await generate_vpn_config(server, telegram_id)
    qr_code_file_path = os.path.join(MEDIA_FOLDER, f"{telegram_id}_{order_id}_vpn_qr.png")
    config_file_path = os.path.join(MEDIA_FOLDER, f"{telegram_id}_{order_id}_vpn.conf")

    await asyncio.to_thread(generate_qr_code, config_content=vpn_config, file_path=qr_code_file_path)
    await write_to_file(config_file_path, vpn_config)

    logger.info(f"Сгенерировал QR код для юзера {telegram_id}")
    await send_document(
        bot,
        telegram_id,
        FSInputFile(config_file_path),
        caption=locale.get("vpn-config-msg"),
    )
    await send_document(
        bot,
        telegram_id,
        FSInputFile(qr_code_file_path),
        caption=locale.get("qr-code-msg"),
    )
